
import Excepciones.ExcepcionExisteNombreDiccionario;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jose Luis Orta
 * colaborador: Albert Alemany Font
 * 
 */
public class VistaDiccionario extends JPanel {
    private CIDiccionario cid;
    private SpringLayout layout;
    private JScrollPane jspPalabras;
    private JTable jtPalabras;
    private SpringLayout layoutPalabras;
    private JButton btnAnadir;
    private JButton btnQuitar;
    private JButton btnModificar;
    private JButton btnBuscar;
    private JTextField txtPalabra;
    private JPanel pNoHayDiccionario;
    private SpringLayout lyPanelNoHayDiccionario;
    private JLabel lbNoHayDiccionario;
    
    private JPanel pDiccionario;
    private SpringLayout lyPanelDiccionario;
    


   
    private JLabel jlPal;



    private DefaultTableModel dtm;


    public VistaDiccionario(CIDiccionario c){
        cid = c;
        inicializar();
    }


    public void limpiar(){
        dtm = construirTableModel(0);
        jtPalabras.setModel(dtm);
    }
    public void cambiarANoDiccionario(){
        pDiccionario.setVisible(false);
        pNoHayDiccionario.setVisible(true);
    }
    public void cambiarADiccionario(){
        pDiccionario.setVisible(true);
        pNoHayDiccionario.setVisible(false);
    }
    public void cargarEnTabla(ArrayList<String> palabras){
        for (int i = 0; i<palabras.size(); i++){
            anadirFilaTabla(palabras.get(i));
        }
    }
    public void seleccionarPalabra(String pal){
        int i=0; 
        boolean enc = false;
        while (i<dtm.getRowCount() && !pal.equals(jtPalabras.getValueAt(i, 0))){
            i++;  
        }
        if (i<dtm.getRowCount()) seleccionarFila(i);
        else cid.noEncontradaPalabra();
                
    }
    public void seleccionarFila(int row){
        
        jtPalabras.setRowSelectionInterval(row, row);
        // Nos devuelve la posición en pixels de una celda en fila,columna
        Rectangle r = jtPalabras.getCellRect(row, 0, false);
        
        // Mueve el scroll para que el rectangulo sea visible
        
        jspPalabras.getVerticalScrollBar().setValue((int)r.getY());
        
    }
    public String preguntarPalabra(){
        return txtPalabra.getText();
    }
    public String preguntarPalabraSeleccionada(){
        return jtPalabras.getValueAt(jtPalabras.getSelectedRow(), 0).toString();
    }
    public void eliminarFilaTabla(int row){
        dtm.removeRow(row);
    }
    public void anadirPalabraATabla(String pal){
        String[] row = {pal};
        dtm.addRow(row);
        jtIrAlFinal();
    }
    public void mensaje(String mensaje){
        mensaje(this,mensaje);
    }
    public void mensaje(Component cent, String mensaje){
        JOptionPane.showMessageDialog(cent, mensaje);
    }
    public int preguntarIndicePalabraSeleccionada(){
        return jtPalabras.getSelectedRow();
        
   
    }
    public void modificarFila(String pal,int row){
       //int rowModel =jtPalabras.getRowSorter().convertRowIndexToModel(row);
       dtm.setValueAt(pal, row, 0);
    }
    public void borrarIK(int i, int k){
        while (i<=(i+k) && i<dtm.getRowCount()){
            dtm.setValueAt("", i, 0);
            i++;
        }
    }
    public void rellenarIK(int i, int k,String[] s){
        int j=0;
        int ii=i;
        while (ii<(i+k) && ii<dtm.getRowCount()){
            dtm.setValueAt(s[j], ii, 0);
            ii++;
            j++;
        }
    }
    public int cuantasFilas(){
        return jspPalabras.getViewport().getHeight()/jtPalabras.getRowHeight()+1;
    }    
    public int queFila(){
       return jspPalabras.getVerticalScrollBar().getValue()/jtPalabras.getRowHeight();
    }
    public void nuevaTabla(int filas){
        dtm=construirTableModel(filas);
        jtPalabras.setModel(dtm);
    }
    
    
    
    private void jtIrAlFinal(){
        jtPalabras.setRowSelectionInterval(dtm.getRowCount()-1, dtm.getRowCount()-1);
        // Nos devuelve la posición en pixels de una celda en fila,columna
        Rectangle r = jtPalabras.getCellRect(dtm.getRowCount()-1, dtm.getColumnCount()-1, true);
        // Mueve el scroll para que el rectangulo sea visible
        jspPalabras.getViewport().scrollRectToVisible (r);
    }
    private void anadirFilaTabla(String palabra){
        String[] fila = new String[1];
        fila[0]=palabra;
        dtm.addRow(fila);
    }
    private DefaultTableModel construirTableModel(int filas){
        DefaultTableModel tm;
        tm= new DefaultTableModel() {
        /*definimos que no se puede editar ninguna celda
          redefiniendo el metodo isCellEditable */
        @Override
        public boolean isCellEditable (int fila, int columna) {
            return false;
        }
        };
       tm.addColumn("Palabras");
       tm.setNumRows(filas);
      /*  TableRowSorter sorter = new TableRowSorter(tm);
        jtPalabras.setRowSorter(sorter);*/
       return tm;
    }
    private void inicializar(){
        
        pDiccionario = new JPanel();
        lyPanelDiccionario = new SpringLayout();
        pNoHayDiccionario = new JPanel();
        lyPanelNoHayDiccionario = new SpringLayout();
        lbNoHayDiccionario=new JLabel("No hay ningun diccionario");
        
        txtPalabra = new JTextField();
        btnAnadir = new JButton("Anadir Palabra");
        btnQuitar = new JButton("Quitar Palabra");
        btnModificar = new JButton("Modificar Palabra");
        btnBuscar = new JButton("Buscar Palabra");
        layout = new SpringLayout ();
        jtPalabras = new JTable();
        jlPal = new JLabel ();
        jspPalabras = new JScrollPane(jtPalabras);
        
        jspPalabras.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){

            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                refrescarTabla();
            }
        });
        
        btnBuscar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
             buscarPalabrasActionPerformed(e);
        }
        });

        btnAnadir.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
            anadirActionPerformed(e);
        }
        });

        btnQuitar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

                    quitarActionPerformed(e);
                
        }
        });

        btnModificar.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {
                try {
                    ModificarPalabraActionPerformed(e);
                } catch (ExcepcionVacio ex) {
                    Logger.getLogger(VistaDiccionario.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        });
        

        jtPalabras.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

        public void valueChanged(ListSelectionEvent e) {
                jtSelectionChanged(e);
            }
        });
        jtPalabras.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        layoutPalabras = new SpringLayout();
        
        jlPal.setSize(30,20);
        jlPal.setText("Palabra:");
        txtPalabra.setPreferredSize(new Dimension(200,20));
        lbNoHayDiccionario.setHorizontalAlignment(SwingConstants.CENTER);
        lbNoHayDiccionario.setVerticalAlignment(SwingConstants.CENTER);
        
        inicializarPanel();
        inicializarPanelBotones();
        inicializarPanelDiccionario();
        inicializarPanelNoHayDiccionario();
        inicializarLayoutPanelNoHayDiccionario();
        inicializarLayoutPanelDiccionario();
        inicializarTabla();
        inicializarLayout();
        montar();
    }
    private void refrescarTabla(){
        cid.refrescarTabla();
    }

    private void jtSelectionChanged(ListSelectionEvent e){
        if (jtPalabras.getSelectedRow()!=-1)
        txtPalabra.setText(jtPalabras.getValueAt(jtPalabras.getSelectedRow(), 0).toString());
    }
    private void inicializarPanelNoHayDiccionario(){
        pNoHayDiccionario.setVisible(true);
        
    }
    private void inicializarLayoutPanelNoHayDiccionario(){
        pNoHayDiccionario.setLayout(lyPanelNoHayDiccionario);
        lyPanelNoHayDiccionario.putConstraint(SpringLayout.NORTH, lbNoHayDiccionario, 0, SpringLayout.NORTH, pNoHayDiccionario);
        lyPanelNoHayDiccionario.putConstraint(SpringLayout.SOUTH, lbNoHayDiccionario, 0, SpringLayout.SOUTH, pNoHayDiccionario);
        lyPanelNoHayDiccionario.putConstraint(SpringLayout.EAST, lbNoHayDiccionario, 0, SpringLayout.EAST, pNoHayDiccionario);
        lyPanelNoHayDiccionario.putConstraint(SpringLayout.WEST, lbNoHayDiccionario, 0, SpringLayout.WEST, pNoHayDiccionario);
    }
    private void inicializarPanelDiccionario(){

        pDiccionario.setVisible(false);
    }
    private void inicializarLayoutPanelDiccionario(){
        pDiccionario.setLayout(lyPanelDiccionario);
        
        
        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, jspPalabras, 20, SpringLayout.NORTH, pDiccionario);
        lyPanelDiccionario.putConstraint(SpringLayout.EAST, jspPalabras, -15, SpringLayout.EAST, pDiccionario);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, jspPalabras, 15, SpringLayout.WEST, pDiccionario);
        lyPanelDiccionario.putConstraint(SpringLayout.SOUTH, jspPalabras, -150, SpringLayout.SOUTH, pDiccionario);
        
  
        
        

        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, btnAnadir, 20, SpringLayout.SOUTH, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, btnAnadir, 10, SpringLayout.WEST, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.EAST, btnAnadir, -5, SpringLayout.HORIZONTAL_CENTER, jspPalabras);
        
        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, btnQuitar, 20, SpringLayout.SOUTH, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, btnQuitar, 5, SpringLayout.HORIZONTAL_CENTER, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.EAST, btnQuitar, -10, SpringLayout.EAST, jspPalabras);

        lyPanelDiccionario.putConstraint(SpringLayout.EAST, btnBuscar, -10, SpringLayout.EAST, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, btnBuscar, 5, SpringLayout.HORIZONTAL_CENTER, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, btnBuscar, 10, SpringLayout.SOUTH, btnQuitar);

        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, btnModificar, 10, SpringLayout.SOUTH, btnAnadir);
        lyPanelDiccionario.putConstraint(SpringLayout.EAST, btnModificar, -5, SpringLayout.HORIZONTAL_CENTER, jspPalabras);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, btnModificar, 10, SpringLayout.WEST, jspPalabras);

        
        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, jlPal, 10, SpringLayout.SOUTH, btnModificar);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, jlPal, 10, SpringLayout.WEST, jspPalabras);
        
        lyPanelDiccionario.putConstraint(SpringLayout.NORTH, txtPalabra, 0, SpringLayout.NORTH, jlPal);
        lyPanelDiccionario.putConstraint(SpringLayout.WEST, txtPalabra, 5, SpringLayout.EAST, jlPal);
        
    }
    private void inicializarTabla() {
        //jtPalabras.setAutoCreateRowSorter(true);
        dtm = construirTableModel(0);
        jtPalabras.setModel(dtm);
        //jspPalabras = new JScrollPane(jtPalabras);
        jtPalabras.setModel(dtm);

    }

   private void buscarPalabrasActionPerformed(ActionEvent e) {
       cid.buscarPalabra();
   }

   private void anadirActionPerformed(ActionEvent e)  {
        
       cid.anadirPalabra();
       
   }
   private void quitarActionPerformed(ActionEvent e){
       cid.eliminarPalabra();
   }
   private void jtMouseClicked(MouseEvent evt){
       int rsel=jtPalabras.rowAtPoint(evt.getPoint());
       
       txtPalabra.setText(jtPalabras.getValueAt(rsel, 0).toString());
   }

 

   private void ModificarPalabraActionPerformed(ActionEvent e)throws ExcepcionVacio {
        cid.modificarPalabra();
   }

 

    private void inicializarPanel(){
        this.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY), "Diccionario"));

    }
    private void inicializarPanelBotones(){
        //botones.setBorder(BorderFactory.createLineBorder(Color.CYAN));

    }

    private void inicializarLayout(){
        this.setLayout(layout);
        
        layout.putConstraint(SpringLayout.WEST, pDiccionario, 0, SpringLayout.WEST, this);
        layout.putConstraint(SpringLayout.EAST, pDiccionario, 0, SpringLayout.EAST, this);
        layout.putConstraint(SpringLayout.NORTH, pDiccionario, 0, SpringLayout.NORTH, this);
        layout.putConstraint(SpringLayout.SOUTH, pDiccionario, 0, SpringLayout.SOUTH, this);
        layout.putConstraint(SpringLayout.WEST, pNoHayDiccionario, 0, SpringLayout.WEST, this);
        layout.putConstraint(SpringLayout.EAST, pNoHayDiccionario, 0, SpringLayout.EAST, this);
        layout.putConstraint(SpringLayout.NORTH, pNoHayDiccionario, 0, SpringLayout.NORTH, this);
        layout.putConstraint(SpringLayout.SOUTH, pNoHayDiccionario, 0, SpringLayout.SOUTH, this);

    }

    

    private void montar(){
        pNoHayDiccionario.add(lbNoHayDiccionario);
        pDiccionario.add(jspPalabras);
        pDiccionario.add(btnAnadir);
        pDiccionario.add(btnQuitar);
        pDiccionario.add(btnModificar);
        pDiccionario.add(btnBuscar);
        pDiccionario.add(txtPalabra);
        pDiccionario.add(jlPal);
        this.add(pDiccionario);
        this.add(pNoHayDiccionario);
    }


        public String preguntarRuta(Component cent,String tipo, String titulo){
        String ruta = "";
        int result;
        JFileChooser jfc = new JFileChooser();
        jfc.setApproveButtonText(tipo);
        jfc.setDialogType(JFileChooser.OPEN_DIALOG);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setDialogTitle(titulo);
        result = jfc.showOpenDialog(cent);
        if (result == JFileChooser.APPROVE_OPTION){
            ruta = jfc.getSelectedFile().getPath();
        }
        return ruta;
    }

    public void anadirTexto(ArrayList<String> lineas, String titulo){
        int size = lineas.size();
        String[] s = new String[size];
        int h;
        int tam = dtm.getRowCount();
        for(h = 0; h < tam; ++h) dtm.removeRow(dtm.getRowCount()-1);
        int i;
        for(i = 0; i < lineas.size(); ++i) {
            s[i] = lineas.get(i);
            dtm.addRow(s);
            jtPalabras.setValueAt(s[i], i, 0);
        }
    }
    public void mostrarError(String textoError,Component cent){
        JOptionPane.showMessageDialog(cent, textoError, "Error", JOptionPane.ERROR_MESSAGE);
        
    }

 


  


}
